package com.fumin.controller;

import com.fumin.Filtter.BussinessException;
import com.fumin.pojo.BusinessResponse;
import com.fumin.pojo.User;
import com.fumin.service.EhcacheService;
import com.fumin.service.UserService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.prefs.BackingStoreException;

/**
 * Created by Lingo on 2018/2/11.
 */
@Controller
public class CaptchaController {

    private Producer kaptchaProducer=null;

    @Autowired
    public void setCaptchaProducer(Producer kaptchaProducer) {
        this.kaptchaProducer = kaptchaProducer;
    }

    @Resource
    EhcacheService ehcacheService;
    @Resource
    UserService userService;

    @RequestMapping("/kaptcha")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String capText = kaptchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = kaptchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }


    @RequestMapping(value = "/promote/message/{userPk}", method = RequestMethod.GET)
    @ResponseBody
    public Object massage(@PathVariable Long userPk,String type,@RequestHeader("User") Long userid){

        if (userPk.longValue()!=userid.longValue()){
            return new BussinessException("-1","无效的请求");
        }
        User user = userService.selectByPrimaryKey(userPk);
        if (user==null){
            throw new BussinessException("-1","用户不存在");
        }
        String phone = user.getMobile_phone();
        BusinessResponse businessResponse = new BusinessResponse();
        boolean exist = ehcacheService.checkPhone(phone);
        if(exist){
            businessResponse.setCode("1");
            businessResponse.setMessage("您的短信验证码请求频率过高！请稍后再试");
            businessResponse.setContent("您的短信验证码请求频率过高！请稍后再试");
            return businessResponse;
        }
        String capText = ehcacheService.getIdentifyingCode(phone,kaptchaProducer);
        String temp = "http://sms.microsoco.com/sms.aspx?action=send&userid=3007&account=hybuzhi&password=123987&" +
                "mobile=%s&" +
                "content=%s&sendTime=&extno=";

        String  contentTemplate = "【soico】 提现验证码：%s，请及时验证，切勿泄露给他人。";
        if ("0".equals(type)){
            contentTemplate = "【soico】 投资验证码：%s，请及时验证，切勿泄露给他人。";
        }

        String content =  String.format(contentTemplate,capText);

        try {
            content = URLEncoder.encode(content,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            businessResponse.setCode("-1");
            businessResponse.setMessage("failed");
            businessResponse.setContent("encoder down, please try later!");
            return businessResponse;
        }

        String  url = String.format(temp,phone,content);
        System.out.println(url);
        try {
            HttpResponse<String> response = Unirest.post(url)
                    .header("cache-control", "no-cache")
                    .asString();

            String messagePlatformResp = response.getBody();
            Document doc  = DocumentHelper.parseText(messagePlatformResp);
            Element  element = doc.getRootElement();
            Iterator iter = element.elementIterator();
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                if ("returnstatus".equals(recordEle.getName())){
                    if (!"Success".equals(recordEle.getTextTrim())){
                        businessResponse.setCode("-1");
                        businessResponse.setMessage("failed");
                        businessResponse.setContent("message platform down, please try later!");
                    }else {
                        businessResponse.setCode("0");
                        businessResponse.setMessage("success");
                        businessResponse.setContent("success!");
                    }
                }
            }

        } catch (UnirestException e) {
            businessResponse.setCode("-1");
            businessResponse.setMessage("failed");
            businessResponse.setContent("短信平台拥堵，请稍后再试！");
            return businessResponse;
        } catch (DocumentException e) {
           e.printStackTrace();
            businessResponse.setCode("-1");
            businessResponse.setMessage("failed");
            businessResponse.setContent("短信平台拥堵，请稍后再试！");
            return businessResponse;
        }
        return businessResponse;
    }


    @RequestMapping(value = "/promote/delete", method = RequestMethod.GET)
    @ResponseBody
    public Object massagedd(String phone){
        BusinessResponse businessResponse = new BusinessResponse();
        ehcacheService.removeIdentifyingCode(phone);


        return businessResponse;
    }

    @RequestMapping(value = "/coin/total", method = RequestMethod.GET)
    @ResponseBody
    public Object getTotalCoin(){
        String total = ehcacheService.selectTotal();
        BusinessResponse businessResponse = new BusinessResponse();
        businessResponse.setCode("0");
        businessResponse.setMessage("success");
        businessResponse.setContent(total);
        return businessResponse;
    }




}